'use strict'

let { Bolg, Op } = require('../modul');


let fn_list = async (ctx, next) => {
    let keyword = ctx.request.query.keyword;
    console.log(keyword);

    if (keyword) {
        let list = await Bolg.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? -1 : parseInt(keyword) },
                    { title: keyword },
                    { digest: keyword },
                    { content: keyword },
                    { variety: keyword },
                    { author: keyword },
                    { createdAt: keyword }
                ]
            },
            order: ['id']
        })

        ctx.body = {
            code: 1000,
            data: list,
            msg: ''
        }
    } else {
        let list = await Bolg.findAll({ order: ['id'] });

        ctx.body = {
            code: 1000,
            data: list,
            msg: ''
        }
    }
}


let fn_getById = async (ctx, next) => {
    let id = ctx.request.params.id;

    let list = await Bolg.findByPk(id);

    ctx.body = {
        code: 1000,
        data: list,
        msg: ''
    }
}


let fn_post = async (ctx, next) => {
    let obj = ctx.request.body;

    await Bolg.create(obj);

    ctx.body = {
        code: 1000,
        data: '',
        msg: ''
    }
}


let fn_put = async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;

    let list = await Bolg.findByPk(id);

    if (list) {
        await Bolg.update(obj, {
            where: {
                id: id
            }
        })

        ctx.body = {
            code: 1000,
            data: '',
            msg: ''
        }
    } else {
        ctx.body = {
            code: 400,
            data: '',
            msg: ''
        }
    }

}

let fn_delete = async (ctx, next) => {
    let id = ctx.request.params.id;

    let list = await Bolg.findByPk(id);

    if (list) {
        await Bolg.destroy({
            where: {
                id: id
            }
        })

        let list = await Bolg.findAll({ order: ['id'] })

        ctx.body = {
            code: 1000,
            data: list,
            msg: ''
        }
    } else {
        ctx.body = {
            code: 400,
            data: '',
            msg: ''
        }
    }

}

module.exports = {
    'get /bolg': fn_list,
    'get /bolg/:id': fn_getById,
    'post /bolg': fn_post,
    'put /bolg/:id': fn_put,
    'delete /bolg/:id': fn_delete,
}